package com.catjiu.wangEditor.controller;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.catjiu.Html2WordConvert;
import com.catjiu.wangEditor.entity.DomNode;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class WangEditorController {
    @Value("${wangEditor.img.download_url}")
    private String downloadUrl;
    Map<String, byte[]> imgDB = new HashMap<String, byte[]>();
    @PostMapping("upload")
    public JSONObject upload(MultipartFile file) throws IOException {
        JSONObject res = new JSONObject();
        res.put("errno",0);
        Map<String,String> data = new HashMap<>();
        String id = UUID.randomUUID().toString();
        imgDB.put(id,file.getBytes());
        data.put("url",downloadUrl+id);
        data.put("alt",id+".png");
        res.put("data",data);
        return res;
    }
    @GetMapping("download/{id}")
    public byte[] download(@PathVariable("id") String id){
        return imgDB.get(id);
    }

    @PostMapping("html2word")
    public void html2Word(@RequestBody String html) throws IOException {
        XWPFDocument word = Html2WordConvert.builder().convert(html);
        OutputStream out =new FileOutputStream("/catjiu/file/out.docx");
        word.write(out);
        out.flush();
        out.close();
    }
}
